import 'package:flutter/material.dart';
import 'package:library_base/constant/constant.dart';
import 'package:library_base/entities/goods_child_entity.dart';
import 'package:library_base/entities/goods_entity.dart';
import 'package:library_base/ext/list_ext.dart';
import 'package:library_base/ext/theme_data_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:library_base/res/colors.dart';
import 'package:library_base/res/gaps.dart';
import 'package:library_base/res/styles.dart';
import 'package:library_base/utils/theme_util.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:library_base/utils/widget_generate_util.dart';
import 'package:library_base/widget/button/gradient_button.dart';
import 'package:library_base/widget/button/ink_bg_well.dart';
import 'package:library_base/widget/dialog/dialog_util.dart';
import 'package:library_base/widget/image/local_image.dart';
import 'package:library_base/widget/multi_state_widget/multi_state_widget.dart';
import 'package:library_base/base/base_list_state.dart';
import 'package:module_administrator/page/create_purchase_order/goos_list/goods_list_controller.dart';

class GoodsListPage extends StatefulWidget {
  const GoodsListPage({Key? key}) : super(key: key);

  @override
  _GoodsListPageState createState() => _GoodsListPageState();
}

class _GoodsListPageState
    extends BaseListState<GoodsEntity, GoodsChildEntity, GoodsListPage, GoodsListController> {
  @override
  GoodsListController registerController() => Get.find<GoodsListController>();

  @override
  void onCreate() {
    super.onCreate();
    setTitle(MultiLanguage.addingGoods.tr);
  }

  @override
  Future<bool> onBackClick() {
    if (baseGetxController!.initlistDataSelected
        .equal(baseGetxController!.listDataSelected.value)) {
      Get.back(result: baseGetxController!.listDataSelected.value);
    } else {
      DialogUtil.showCupertinoAlertDialog(context,
          title: MultiLanguage.confirmAdd.tr,
          content: MultiLanguage.change.tr,
          cancel: MultiLanguage.cancel.tr,
          confirm: MultiLanguage.determine.tr, cancelPressed: () {
        Get.back();
        Get.back(result: baseGetxController!.initlistDataSelected);
      }, confirmPressed: () async {
        Get.back();
        Get.back(result: baseGetxController!.listDataSelected.value);
      });
    }
    return Future.value(false);
  }

  @override
  Widget? getMainWidget(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        onBackClick();
        return false;
      },
      child: MultiStateWidget(
        emptyWidget: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              LocalImage('admin_empty', package: Constant.packAdmin(), width: 0.6.sw),
              Text(MultiLanguage.noSuchProduct.tr, style: TextStyles.textSecondary28),
              SizedBox(height: 80.h),
              Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                GradientButton(
                  ThemeUtil.getTheme(),
                  width: 0.4.sw,
                  height: 80.w,
                  text: MultiLanguage.backToList.tr,
                  onPressed: baseGetxController!.backToList,
                ),
                SizedBox(width: 40.w),
                GradientButton(
                  ThemeUtil.getTheme(),
                  width: 0.4.sw,
                  height: 80.w,
                  text: MultiLanguage.reload.tr,
                  onPressed: baseGetxController!.tryReLoad,
                ),
              ])
            ]),
        controller: baseGetxController!.multiControllerOut,
        child: Container(
          color: Colors.white,
          child: Column(
            children: [
              buildHeader(),
              Expanded(
                child: getListView(context, baseGetxController),
              ),
              Container(
                  padding: EdgeInsets.only(top: 21.w, right: 24.w),
                  height: 166.w,
                  decoration: const BoxDecoration(color: Colors.white, boxShadow: [
                    BoxShadow(
                        offset: Offset(0.0, 5.0), //阴影xy轴偏移量
                        blurRadius: 15.0, //阴影模糊程度
                        spreadRadius: -11 //阴影扩散程度
                        )
                  ]),
                  alignment: Alignment.topRight,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Expanded(
                          child: Stack(children: [
                        Positioned(
                          left: 24.w,
                          top: 8.w,
                          child: GestureDetector(
                            onTap: onShowSelectedGoods,
                            child: LocalImage('admin_goods_cart',
                                package: Constant.packAdmin(), width: 56.w, height: 56.w),
                          ),
                        ),
                        Positioned(
                          left: 100.w,
                          top: 20.w,
                          child: GetBuilder<GoodsListController>(
                            builder: (logic) {
                              return Text(MultiLanguage.selectedGoodsCount
                                  .trArgs(["${logic.listDataSelected.length}"]));
                            },
                          ),
                        ),
                      ])),
                      GetBuilder<GoodsListController>(
                        builder: (logic) {
                          return GradientButton(
                            ThemeUtil.getTheme(),
                            width: 184.w,
                            height: 77.w,
                            text: MultiLanguage.determine.tr,
                            onPressed: baseGetxController!.listDataSelected.value.isEmpty
                                ? null
                                : () {
                                    Get.back(result: baseGetxController!.listDataSelected.value);
                                  },
                          );
                        },
                      ),
                    ],
                  )),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildHeader() {
    return Container(
      color: ThemeUtil.getTheme().colorScheme.secondary,
      height: 116.w,
      child: Row(
        children: <Widget>[
          Expanded(
            child: Container(
                alignment: Alignment.center,
                height: double.infinity,
                margin: EdgeInsets.only(left: 24.w, top: 24.w, bottom: 24.w),
                decoration: BoxDecoration(
                  color: ThemeUtil.getTheme().secondaryBgColor(),
                  borderRadius: const BorderRadius.all(Radius.circular(30.0)),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Gaps.hGap24,
                    LocalImage('admin_search',
                        package: Constant.packAdmin(), width: 26.w, height: 26.w),
                    Gaps.hGap24,
                    Expanded(
                      child: Container(
                        alignment: Alignment.center,
                        height: double.infinity,
                        width: double.infinity,
                        child: TextField(
                          onChanged: (value) {
                            if (baseGetxController!.keyWord.value != value) {
                              baseGetxController!.keyWord.value = value;
                              if (value.isEmpty) {
                                baseGetxController!.tryReLoad();
                              }
                            }
                          },
                          autofocus: false,
                          controller: baseGetxController!.keyWorkSearchController,
                          textAlignVertical: TextAlignVertical.center,
                          decoration: InputDecoration(
                            focusedBorder: const OutlineInputBorder(
                                borderSide: BorderSide(width: 0, color: Colors.transparent)),
                            disabledBorder: const OutlineInputBorder(
                                borderSide: BorderSide(width: 0, color: Colors.transparent)),
                            enabledBorder: const OutlineInputBorder(
                                borderSide: BorderSide(width: 0, color: Colors.transparent)),
                            contentPadding: const EdgeInsets.symmetric(vertical: 0),
                            border: InputBorder.none,
                            labelStyle: TextStyles.textNormal28,
                            hintText: MultiLanguage.pleaseEnterProduct.tr,
                            hintStyle: TextStyles.textSixthColor28,
                            suffixIcon: GetBuilder<GoodsListController>(builder: (logic) {
                              return baseGetxController!.keyWord.isNotEmpty
                                  ? IconButton(
                                      iconSize: 30.w,
                                      icon: Icon(Icons.close, color: Colours.gray_400, size: 30.w),
                                      onPressed: () {
                                        baseGetxController!.keyWorkSearchController.text = '';
                                        baseGetxController!.keyWord.value = "";
                                        baseGetxController!.tryReLoad();
                                      },
                                    )
                                  : gapZero;
                            }),
                          ),
                        ),
                      ),
                    ),
                  ],
                )),
          ),
          textInkBgWell(MultiLanguage.search.tr, onTap: baseGetxController!.onSearch)
        ],
      ),
    );
  }

  ///显示选中的商品列表
  void onShowSelectedGoods() {
    if (baseGetxController!.listDataSelected.isEmpty) {
      ToastUtil.normal(MultiLanguage.pleaseSelectTheItemBeforeProceeding.tr);
      return;
    }
    var map = {};
    map['CallBack'] = (List<GoodsChildEntity> goods) {
      baseGetxController!.listDataSelected.value = goods;
      for (var element in baseGetxController!.listData.value) {
        element.isSelect = false;
      }
      for (var elementSelected in baseGetxController!.listDataSelected.value) {
        for (var element in baseGetxController!.listData.value) {
          if (element.id == elementSelected.id) {
            element.isSelect = true;
            elementSelected = element;
          }
        }
      }
      setState(() {});
    };
    var temporaryGoods =
        List<GoodsChildEntity>.generate(baseGetxController!.listDataSelected.length, (int index) {
      return baseGetxController!.listDataSelected[index];
    }, growable: true);

    map['listDataSelected'] = temporaryGoods;
    DialogUtil.showBottomGoodsListDialog(arguments: map);
  }

  @override
  List<Widget> buildListItem(BuildContext context) {
    var widgets = <Widget>[];
    baseGetxController!.listData.value.forEachIndexed((index, element) {
      widgets.add(GetBuilder<GoodsListController>(
        builder: (logic) {
          return GenerateWidgetUtil.getGoodsItem(element, onTap: baseGetxController!.onItemClick);
        },
      ));
    });
    return widgets;
  }
}
